package cn.gson.financial.controller;

import cn.gson.financial.annotation.IgnoresLogin;
import cn.gson.financial.base.BaseCrudController;
import cn.gson.financial.kernel.common.DoubleValueUtil;
import cn.gson.financial.kernel.controller.JsonResult;
import cn.gson.financial.kernel.model.entity.AccountingCategoryDetails;
import cn.gson.financial.kernel.model.entity.ReportTemplate;
import cn.gson.financial.kernel.model.vo.DepartmentOrProjectVO;
import cn.gson.financial.kernel.model.vo.ReportBMXMVo;
import cn.gson.financial.kernel.model.vo.ReportDataVo;
import cn.gson.financial.kernel.service.AccountingCategoryDetailsService;
import cn.gson.financial.kernel.service.AccountingCategoryService;
import cn.gson.financial.kernel.service.AllSelectService;
import cn.gson.financial.kernel.service.ReportBottomTableService;
import cn.gson.financial.kernel.service.ReportTemplateService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 报表
 */

@RestController
@RequestMapping("/report/template")
public class ReportTemplateController extends BaseCrudController<ReportTemplateService, ReportTemplate> {
    @Autowired
    private ReportBottomTableService reportBottomTableService;

    @Autowired
    private AccountingCategoryDetailsService categoryService;

    /**
     * 三大报表
     * @param id
     * @param accountDate
     * @return
     */
    @IgnoresLogin
    @GetMapping("view/{id:\\d+}")
    public JsonResult view(@PathVariable Long id, @RequestParam Date accountDate) {
        return JsonResult.successful(service.view(this.accountSetsId, id, accountDate));
    }



    /**
     * 三大报表 动态
     * @param
     * @param
     * @return
     */
    @IgnoresLogin
    @PostMapping("/viewsReport")
    public JsonResult views2(@RequestBody ReportBMXMVo vo) {
        System.out.println(vo);
        return JsonResult.successful(service.viewReport(this.accountSetsId,vo.getReportTemlateId(),vo.getSTime(),vo.getETime()));
    }

    private static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 部门 项目 利润表
     * @return
     */
    @IgnoresLogin
    @PostMapping("/views")
    public JsonResult view2(@RequestBody ReportBMXMVo vo) {
        return JsonResult.successful(this.getViews(vo));
    }

    public List<DepartmentOrProjectVO> getViews(ReportBMXMVo vo){
        //获取月份期间   ---季度滤过
        String sTime = "";
        String eTime = "";
        try {
            if(vo.getETime() == null || vo.getETime().equals("")){
                Date date = new SimpleDateFormat("yyyy-MM").parse(vo.getSTime());
                int days = getDaysOfMonth(date);
                sTime = vo.getSTime()+"-01";
                eTime = vo.getSTime()+"-"+days;
            }else {
                sTime = vo.getSTime();
                eTime = vo.getETime();
            }
        }catch (Exception e){

        }

        List<DepartmentOrProjectVO> list = new ArrayList<>();

        Map<Integer, ReportDataVo> acountMap = new HashMap<>();

        for(int i = 0; i < vo.getIds().size(); i++){
            LambdaQueryWrapper<AccountingCategoryDetails> qw = Wrappers.lambdaQuery();
            qw.eq(AccountingCategoryDetails::getId,vo.getIds().get(i));

            DepartmentOrProjectVO departmentOrProjectVO = new DepartmentOrProjectVO();
            AccountingCategoryDetails one = categoryService.getOne(qw);
            if (one != null){
                departmentOrProjectVO.setDepartentProjectName(categoryService.getOne(qw).getName());
                Map<Integer, ReportDataVo> map = service.view2(
                        this.accountSetsId,
                        vo.getReportTemlateId(),
                        sTime,
                        eTime,
                        vo.getIds().get(i));
                departmentOrProjectVO.setMap(map);
                list.add(departmentOrProjectVO);
                // 合计 本期 季度
                List<Integer> keyList = new ArrayList<>(map.keySet());
                for(int j = 0; j < keyList.size(); j++){
                    ReportDataVo reportDataVo = copy(map.get(keyList.get(j)));
                    if(acountMap.get(keyList.get(j)) == null){
                        acountMap.put(keyList.get(j), reportDataVo);
                    }else {
                        ReportDataVo reportDataVoTemp =  copy(acountMap.get(keyList.get(j)));
                        reportDataVoTemp.setCurrentPeriodAmount(DoubleValueUtil.getNotNullVal(reportDataVoTemp.getCurrentPeriodAmount())+DoubleValueUtil.getNotNullVal(reportDataVo.getCurrentPeriodAmount()));
                        reportDataVoTemp.setCurrentYearAmount(DoubleValueUtil.getNotNullVal(reportDataVoTemp.getCurrentYearAmount())+DoubleValueUtil.getNotNullVal(reportDataVo.getCurrentYearAmount()));
                        acountMap.put(keyList.get(j), reportDataVoTemp);

                    }
                }
            }
        }
        DepartmentOrProjectVO departmentOrProjectVOs = new DepartmentOrProjectVO();
        departmentOrProjectVOs.setDepartentProjectName("合计");
        departmentOrProjectVOs.setMap(acountMap);
        list.add(departmentOrProjectVOs);
        return list;
    }

    private ReportDataVo copy(ReportDataVo vo){
        ReportDataVo reportDataVo1 = new ReportDataVo();
        reportDataVo1.setItemId(vo.getItemId());
        reportDataVo1.setCurrentYearAmount(vo.getCurrentYearAmount());
        reportDataVo1.setCurrentPeriodAmount(vo.getCurrentPeriodAmount());
        return reportDataVo1;
    }
//    @GetMapping("viewBottom/{id:\\d+}")
//    public JsonResult viewBottom(@PathVariable Long id, @RequestParam String accountDate) {
//        return JsonResult.successful(reportBottomTableService.view(this.accountSetsId, id, accountDate));
//    }


    @GetMapping("viewBottomG/{id:\\d+}")
    public JsonResult viewBottomG(@PathVariable Long id, @RequestParam String sTime, @RequestParam String eTime) {
        return JsonResult.successful(reportBottomTableService.viewG(this.accountSetsId, id, sTime,eTime));
    }
}